package cn.bigcontainer.alt.meta.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import cn.bigcontainer.alt.common.entity.BigMap;
import cn.bigcontainer.alt.common.util.WoJsonKit;

@MappedTypes({BigMap.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class BigMapHandler extends BaseTypeHandler<BigMap> {

    private BigMap parse(String json) {
        return json != null && json.length() != 0 ? WoJsonKit.readAsType(json, BigMap.class) : new BigMap();
    }

    private String toJsonString(Object obj) {
        return WoJsonKit.writeAsString(obj);
    }

    public BigMap getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.parse(rs.getString(columnName));
    }

    public BigMap getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.parse(rs.getString(columnIndex));
    }

    public BigMap getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.parse(cs.getString(columnIndex));
    }

    public void setNonNullParameter(PreparedStatement ps, int columnIndex, BigMap parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(columnIndex, this.toJsonString(parameter));
    }
}
